package db

import (
	"context"
	"fmt"

	"core/contract/db"
	dbEnum "core/enum/db"
	"core/model/config"
)

type Factory struct {
	db map[dbEnum.Value]db.IDb
}

func (f Factory) Build(ctx context.Context, v ...dbEnum.Value) db.IDb {
	t := dbEnum.Mysql
	if len(v) > 0 {
		t = v[0]
	}

	dbSvc, ok := f.db[t]
	if !ok {
		panic(fmt.Sprintf("无效db类型:%v", v))
	}

	dbSvc.WithContext(ctx)
	return dbSvc
}

func NewDbFactory(config *config.Config) (db.IDbFactory, func(), error) {
	mysql, clearUp, err := newMysqlSvc(config)
	if err != nil {
		return nil, func() {}, err
	}

	return Factory{
		db: map[dbEnum.Value]db.IDb{
			dbEnum.Mysql: mysql,
		},
	}, clearUp, nil
}
